<template>
  <div class="sidebar">
    <div class="sidebar-header">
      <input
        v-model="searchKey"
        type="text"
        placeholder="搜索用户或聊天"
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <button class="add-button" @click="showAddOptions = !showAddOptions">+</button>
      <div v-if="showAddOptions" class="add-options">
        <button @click="handleCreateGroupClick">发起群聊</button>
        <button @click="handleAddFriendClick">添加朋友</button>
      </div>
    </div>
    
    <div v-if="showSearchResults" class="search-results">
      <div v-if="searchResult" class="search-result-item">
        <img :src="searchResult.avatarUrl || '/images/avatar-default.png'" alt="头像" class="avatar">
        <div class="user-info">
          <div class="username">{{ searchResult.userName }}</div>
          <div class="user-relation" v-if="isFriend">已是好友</div>
          <div class="user-relation" v-else-if="hasPendingRequest">等待对方回复</div>
          <textarea 
            v-else 
            v-model="addFriendReason" 
            class="reason-input"
            placeholder="请输入打招呼内容..."
            rows="2"
          ></textarea>
        </div>
        <button class="action-btn" 
                @click="handleUserAction" 
                :disabled="isProcessing || (!isFriend && !addFriendReason.trim())">
          {{ isFriend ? '发起聊天' : (isProcessing ? '处理中...' : '添加好友') }}
        </button>
      </div>
      <div v-else-if="searchKey.trim() && !searching" class="no-result">
        未找到相关用户
      </div>
    </div>
    
    <ul class="contact-list">
      <li
        v-for="contact in filteredContacts"
        :key="contact.id"
        @click="selectContact(contact)"
        :class="{ active: selectedContact === contact }"
      >
        <img :src="contact.avatar" alt="avatar" class="contact-avatar" />
        <div class="contact-info">
          <div class="contact-name-time">
            <div class="contact-name">
              <span v-if="contact.isGroup" class="group-indicator">群聊</span>
              {{ contact.name }}
            </div>
            <div class="contact-time">{{ contact.lastTime }}</div>
            <div v-if="contact.unreadCount > 0" class="unread-badge">{{ contact.unreadCount }}</div>
          </div>
          <div class="contact-last-msg">
            {{ contact.lastMsg }}
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>
<script setup>
import { ref, computed, defineEmits, watch, onMounted, onUnmounted } from "vue";
import axios from "axios";
import request from '../utils/request';

const emit = defineEmits(["contact-selected", "update-contacts", "create-group-click", "go-to-chat", "send-friend-request"]);

const showAddOptions = ref(false);
const searchKey = ref('');
const searchResult = ref(null);
const showSearchResults = ref(false);
const searching = ref(false);
const isProcessing = ref(false);
const friendList = ref([]);
const friendRequests = ref([]);
const addFriendReason = ref('');

// 定时器变量，用于自动刷新
let refreshTimer = null;

const props = defineProps({
  externalContacts: {
    type: Array,
    default: () => [],
  },
});
const contacts = ref([]);
const userId = ref(localStorage.getItem("userId"));
const currentDialogueId = ref(localStorage.getItem("currentDialogueId"));

const isFriend = computed(() => {
  if (!searchResult.value || !friendList.value.length) return false;
  return friendList.value.some(friend => friend.id === searchResult.value.id);
});

const hasPendingRequest = computed(() => {
  if (!searchResult.value) return false;
  
  const outgoing = friendRequests.value.some(req => 
    req.toUserId === searchResult.value.id && req.status === 'pending'
  );
  
  const incoming = friendRequests.value.some(req => 
    req.fromUserId === searchResult.value.id && req.status === 'pending'
  );
  
  return outgoing || incoming;
});

// 时间格式化函数 - 修改为"月/日 时:分"格式
const formatTime = (timeStr) => {
  try {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const month = date.getMonth() + 1; // 月份从0开始，需要+1
    const day = date.getDate();
    const hours = date.getHours().toString().padStart(2, '0'); // 确保两位数
    const minutes = date.getMinutes().toString().padStart(2, '0'); // 确保两位数
    
    // 格式化为 "8/5 23:46" 这样的形式
    return `${month}/${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error("时间格式化错误:", error);
    return timeStr;
  }
};

const loadDialogueList = async () => {
  try {
    if (!userId.value) {
      console.error("未找到用户ID");
      return;
    }
    const response = await api.get("/user/getdialoguelist", {
      params: { userId: userId.value },
    });
    if (response.data.code === "SUCCESS") {
      let dialogues = response.data.data || [];
      
      // 按最后一条消息时间排序（最新的在前）
      dialogues.sort((a, b) => {
        const timeA = new Date(a.lastTime).getTime();
        const timeB = new Date(b.lastTime).getTime();
        return timeB - timeA;
      });

      contacts.value = dialogues.map((dialogue) => {
        const users = dialogue.duserResponses;
        const isGroupChat = users.length > 1;
        let name, avatar;
        if (isGroupChat) {
          name = users.map((user) => user.userName).join(", ");
          avatar = "/images/group1.jpg";
        } else {
          const friend = users.find((user) => user.id !== parseInt(userId.value));
          if (friend) {
            name = friend.userName;
            avatar = friend.avatarUrl || "/images/avatar-default.png";
          } else {
            name = users[0].userName;
            avatar = localStorage.getItem("avatarUrl") || "/images/avatar-default.png";
          }
        }
        return {
          id: dialogue.dialogueId,
          name: name,
          avatar: avatar,
          lastMsg: dialogue.content || "暂无消息",
          lastTime: dialogue.lastTime ? formatTime(dialogue.lastTime) : "无消息",
          isGroup: isGroupChat,
          users: users,
          dialogueId: dialogue.dialogueId,
          unreadCount: 0,
          messages: []
        };
      });
    } else {
      console.error("获取会话列表失败:", response.data.errMsg);
    }
  } catch (error) {
    console.error("获取会话列表失败:", error);
  }
};

const loadFriendList = async () => {
  try {
    const userId = localStorage.getItem('userId');
    const res = await request.get('/user/getfriendlist', {
      params: { userId }
    });
    if (res.data.code === 'SUCCESS') {
      friendList.value = res.data.data || [];
    }
  } catch (error) {
    console.error('加载好友列表失败', error);
  }
};

const loadFriendRequests = async () => {
  try {
    const userId = localStorage.getItem('userId');
    const res = await request.get('/user/getRequestMessage', {
      params: { userId }
    });
    if (res.data.code === 'SUCCESS') {
      friendRequests.value = res.data.data || [];
    }
  } catch (error) {
    console.error('加载好友请求失败', error);
  }
};

const handleSearch = async () => {
  if (!searchKey.value.trim()) {
    searchResult.value = null;
    showSearchResults.value = false;
    return;
  }
  
  const matchedContact = contacts.value.find(contact => 
    contact.name.toLowerCase().includes(searchKey.value.trim().toLowerCase())
  );
  
  if (matchedContact) {
    searchResult.value = null;
    showSearchResults.value = false;
    return;
  }
  
  try {
    searching.value = true;
    const res = await request.get('/user/getUserList', {
      params: { telephone: searchKey.value.trim() }
    });
    if (res.data.code === 'SUCCESS') {
      searchResult.value = res.data.data;
    } else {
      searchResult.value = null;
    }
    showSearchResults.value = true;
  } catch (error) {
    console.error('搜索用户失败', error);
    searchResult.value = null;
    showSearchResults.value = true;
  } finally {
    searching.value = false;
  }
};

const handleUserAction = async () => {
  if (!searchResult.value) return;
  
  if (!isFriend.value && !addFriendReason.value.trim()) {
    alert('请输入打招呼内容');
    return;
  }
  
  isProcessing.value = true;
  try {
    if (isFriend.value) {
      const res = await request.get('/user/getfrienddialogue', {
        params: {
          userId: userId.value,
          friendId: searchResult.value.id
        }
      });
      
      const dialogueId = res.data.data;
      const contact = {
        id: dialogueId,
        name: searchResult.value.userName,
        avatar: searchResult.value.avatarUrl || '/images/avatar-default.png',
        isGroup: false,
        dialogueId: dialogueId,
        users: [{
          id: searchResult.value.id,
          userName: searchResult.value.userName,
          avatarUrl: searchResult.value.avatarUrl
        }]
      };
      
      emit('go-to-chat', contact);
    } else {
      const fromUserId = localStorage.getItem('userId');
      const fromUserName = localStorage.getItem('userName');
      
      const requestData = {
        toUserId: searchResult.value.id,
        toUserName: searchResult.value.userName,
        fromUserId: parseInt(fromUserId),
        fromName: fromUserName,
        reason: addFriendReason.value.trim()
      };
      
      await emit('send-friend-request', requestData);
      alert('好友请求已发送');
      
      addFriendReason.value = '';
      loadFriendRequests();
    }
    
    searchKey.value = '';
    searchResult.value = null;
    showSearchResults.value = false;
  } catch (error) {
    console.error('操作失败', error);
    alert('操作失败：' + (error.message || '网络异常'));
  } finally {
    isProcessing.value = false;
  }
};

const handleAddFriendClick = () => {
  showAddOptions.value = false;
  searchKey.value = '';
  searchResult.value = null;
  addFriendReason.value = '';
  showSearchResults.value = false;
  setTimeout(() => {
    const input = document.querySelector('.search-input');
    input?.focus();
  }, 0);
};

const handleCreateGroupClick = () => {
  emit("create-group-click");
  showAddOptions.value = false;
};

onMounted(async () => {
  await loadDialogueList();
  await loadFriendList();
  await loadFriendRequests();
  const searchInput = document.querySelector('.search-input');
  if (searchInput) {
    searchInput.addEventListener('focus', () => {
      if (searchKey.value.trim()) {
        handleSearch();
      }
    });
  }

  // 启动30秒自动刷新会话列表
  refreshTimer = setInterval(() => {
    console.log('自动刷新会话列表...');
    loadDialogueList();
  }, 30000); // 30000毫秒 = 30秒
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
    console.log('自动刷新定时器已清除');
  }
});

watch(
  () => props.externalContacts,
  (newContacts) => {
    newContacts.forEach((newContact) => {
      if (!contacts.value.some((c) => c.id === newContact.id)) {
        contacts.value.push({
          ...newContact,
          unreadCount: 0,
        });
        sortContactsByTime();
      }
    });
  },
  { deep: true }
);

watch(currentDialogueId, (newId) => {
  if (newId) {
    resetUnreadCount(newId);
  }
});

const sortContactsByTime = () => {
  contacts.value.sort((a, b) => {
    const getTime = (contact) => {
      if (contact.messages && contact.messages.length > 0) {
        return new Date(contact.messages[contact.messages.length - 1].time).getTime();
      }
      return new Date(contact.lastTime).getTime();
    };
    
    return getTime(b) - getTime(a);
  });
};

const processedContacts = computed(() => {
  return contacts.value.map((contact) => {
    const lastMessage = contact.messages?.length
      ? contact.messages[contact.messages.length - 1]
      : null;
    return {
      ...contact,
      lastTime: lastMessage?.time ? formatTime(lastMessage.time) : contact.lastTime,
      lastMsg: lastMessage?.content || contact.lastMsg,
    };
  });
});

const filteredContacts = computed(() => {
  const key = searchKey.value.trim().toLowerCase();
  if (!key) return processedContacts.value;
  
  return processedContacts.value.filter((contact) =>
    contact.name.toLowerCase().includes(key)
  );
});

const selectedContact = ref(null);
const selectContact = (contact) => {
  selectedContact.value = contact;
  currentDialogueId.value = contact.dialogueId;
  emit("contact-selected", {
    ...contact,
    dialogueId: contact.dialogueId,
  });
  localStorage.setItem("currentDialogueId", contact.dialogueId);
  showSearchResults.value = false;
};

const updateWithNewMessage = (contactId, newMsg) => {
  const targetContact = contacts.value.find((c) => c.id === contactId);
  if (targetContact) {
    targetContact.messages = [...(targetContact.messages || []), newMsg];
    targetContact.lastMsg = newMsg.content;
    targetContact.lastTime = formatTime(newMsg.time);

    if (!newMsg.isSelf && contactId !== currentDialogueId.value) {
      targetContact.unreadCount = (targetContact.unreadCount || 0) + 1;
    }

    const index = contacts.value.findIndex(c => c.id === contactId);
    if (index > -1) {
      const [movedContact] = contacts.value.splice(index, 1);
      contacts.value.unshift(movedContact);
    }
  }
};

const resetUnreadCount = (contactId) => {
  const targetContact = contacts.value.find((c) => c.id === contactId);
  if (targetContact) {
    targetContact.unreadCount = 0;
  }
};

const api = axios.create({
  baseURL: "/api",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

defineExpose({
  loadDialogueList,
  updateWithNewMessage,
  resetUnreadCount,
  loadFriendRequests
});
</script>
<style scoped>
.sidebar {
  width: 320px;
  background-color: rgba(255, 255, 255, 0.6);
  border-right: 1px solid #e1d7d7;
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: relative;
}
.sidebar-header {
  padding: 10px;
  border-bottom: 1px solid #ffffff;
  display: flex;
  align-items: center;
}
.search-input {
  width: 100%;
  padding: 8px;
  border: 1px solid rgba(233, 226, 226, 0.7);
  border-radius: 4px;
  margin-right: 10px;
}
.add-button {
  background-color: #ffffff;
  color: rgb(158, 156, 156);
  border: none;
  width: 30px;
  height: 30px;
  font-size: 20px;
  cursor: pointer;
}
.add-button:hover {
  background-color: #e2e9e5;
}
.add-options {
  position: absolute;
  top: 50px;
  right: 10px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  width: 120px;
  z-index: 10;
}
.add-options button {
  border: none;
  background: none;
  padding: 8px 12px;
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}
.add-options button:hover {
  background-color: #f5f5f5;
}
.add-options button:not(:last-child) {
  border-bottom: 1px solid #eee;
}
.contact-list {
  list-style: none;
  margin: 0;
  padding: 0;
  overflow-y: auto;
  flex: 1;
}
.contact-list li {
  padding: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ffffff;
  position: relative;
}
.contact-list li:hover {
  background-color: rgba(255, 255, 255, 0.7);
}
.contact-list li.active {
  background-color: #ffffff;
}
.contact-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}
.contact-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}
.contact-name-time {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
}
.contact-name {
  font-weight: bold;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.group-indicator {
  background-color: #95ec69;
  color: #fff;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 10px;
  margin-right: 4px;
}
.contact-time {
  font-size: 10px;
  color: #999;
  white-space: nowrap;
}
.contact-last-msg {
  font-size: 12px;
  color: #999;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.unread-badge {
  background-color: #ff0000;
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 50%;
  min-width: 20px;
  text-align: center;
  position: absolute;
  right: 10px;
  top: 10px;
}
.search-results {
  border-bottom: 1px solid #eee;
  padding: 10px;
}
.search-result-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}
.search-result-item .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}
.search-result-item .user-info {
  flex: 1;
  margin: 0 15px;
}
.search-result-item .username {
  font-weight: 500;
  margin-bottom: 4px;
}
.search-result-item .user-relation {
  font-size: 12px;
  color: #666;
}
.search-result-item .action-btn {
  padding: 6px 12px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.search-result-item .action-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.no-result {
  text-align: center;
  padding: 15px;
  color: #999;
  font-size: 14px;
}
.reason-input {
  width: 100%;
  padding: 6px 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  font-size: 12px;
  resize: none;
  margin-top: 4px;
  box-sizing: border-box;
}
.reason-input:focus {
  outline: none;
  border-color: #07c160;
}
</style>
